<?php

namespace App\Http\Controllers\Wechat;

use App\Models\SatisfactionSurvey;
use App\Models\SatisfactionSurveyReply;
use App\Validate\SatisfactionSurveyValidate;
use Illuminate\Support\Facades\DB;

/**
 * 满意度调查类
 * Class Survey
 * @package app\api\controller
 */
class SatisfactionSurveyController extends CommonController
{


    // 自动验证
    public $validate = null;
    public $model = null;
    public $surveyReply = null;

    /**
     * 实例化满意度调查验证类
     * Survey constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->validate = new SatisfactionSurveyValidate();
        $this->model = new SatisfactionSurvey();
        $this->surveyReply = new SatisfactionSurveyReply();
    }

    /**
     * 满意度调查列表
     * @param page 默认为 1
     * @param limit 限制条数 默认为 10
     * @param keywords 检索内容
     * @param is_play int 是否发布 1.发布 2.未发布    默认1
     */
    public function lists()
    {
        $page = intval($this->request->page) ?: 1;
        $limit = $this->request->limit ?: 10;
        $keywords = $this->request->keywords;

        // 获取数据
        $res = $this->model->select('id', 'survey_name', 'intro', 'start_time', 'end_time', 'create_time')
            ->where("is_del", 1)
            ->where(function ($query) use ($keywords) {
                if (!empty($keywords)) {
                    $query->where('survey_name', 'like', "%$keywords%");
                }
            })
            ->where('is_play', 1)
            ->orderByDesc("end_time")
            ->orderByDesc("id")
            ->paginate($limit)
            ->toArray();

        $res = $this->disPageData($res);
        foreach ($res['data'] as $key => $val) {
            if ($val['start_time'] > date('Y-m-d H:i:s')) {
                $res['data'][$key]['status'] = 1; //未开始
            } else if ($val['end_time'] < date('Y-m-d H:i:s')) {
                $res['data'][$key]['status'] = 3; //已结束
            } else {
                $res['data'][$key]['status'] = 2; //进行中
            }

            $res['data'][$key]['intro'] = strip_tags($val['intro']);
        }
        // 反馈数据
        if ($res['data']) {
            return $this->returnApi(200, "获取成功", true, $res);
        }
        return $this->returnApi(203, "暂无数据");
    }


    /**
     * 满意度调查详情
     * @param $id ：满意度调查id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];

        // 获取满意度调查是否存在
        $res = $this->model->select('id', 'survey_name', 'intro', 'start_time', 'end_time', 'create_time', 'day_number', 'total_number')
            ->where("is_del", 1)
            ->where("is_play", 1)
            ->find($this->request->id);

        if (empty($res)) {
            return $this->returnApi(203, "暂无数据");
        }

        //获取用户提交次数
        list($is_can_submit, $not_submit_msg) = $this->surveyReply->isCanSubmit($res, $this->request->id, $user_id);
        if ($is_can_submit === false) {
            return $this->returnApi(201, $not_submit_msg);
        }

        if ($res['start_time'] > date('Y-m-d H:i:s') || $res['end_time'] < date('Y-m-d H:i:s')) {
            return $this->returnApi(201, "当前时间不在范围内"); //已过期或未开始
        }

        return $this->returnApi(200, "获取成功", true, $res);
    }


    /**
     * 提交满意度调查
     * @param token 用户token
     * @param id 满意度调查id
     * @param username 用户名
     * @param tel 电话号码
     * @param is_satisfaction 是否满意  1 满意  2 不满意
     */
    public function reply()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('wx_reply')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $user_id = $this->request->user_info['id'];
        // 获取满意度调查是否存在
        $res = $this->model->select('id', 'survey_name', 'intro', 'start_time', 'end_time', 'create_time', 'day_number', 'total_number')
            ->where("is_del", 1)
            ->where("is_play", 1)
            ->find($this->request->id);

        if (empty($res)) {
            return $this->returnApi(203, "满意度调查不存在");
        }
        if ($res['start_time'] > date('Y-m-d H:i:s') || $res['end_time'] < date('Y-m-d H:i:s')) {
            return $this->returnApi(201, "当前时间不在范围内"); //已过期或未开始
        }

        //获取用户提交次数
        list($is_can_submit, $not_submit_msg) = $this->surveyReply->isCanSubmit($res, $this->request->id, $user_id);
        if (!$is_can_submit) {
            return $this->returnApi(201, $not_submit_msg); //用户提交次数已达上限
        }

        DB::beginTransaction();
        try {
            $this->surveyReply->add([
                'survey_id' => $this->request->id,
                'date' => date('Y-m-d'),
                'username' => $this->request->username,
                'tel' => $this->request->tel,
                'is_satisfaction' => $this->request->is_satisfaction,
                'user_id' => $user_id,
            ]);

            DB::commit();
            return $this->returnApi(200, "提交成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage() ? $e->getMessage() : "提交失败");
        }
    }
    /**
     * 我的满意度调查列表
     * @param page 默认为 1
     * @param limit 限制条数 默认为 10
     * @param keywords 检索内容
     */
    public function myReplyList()
    {
        $user_id = $this->request->user_info['id'];
        $page = intval($this->request->page) ?: 1;
        $limit = $this->request->limit ?: 10;
        $survey_id = $this->request->survey_id;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;

        // 获取数据
        $res = $this->surveyReply->lists($survey_id, $user_id, null, null, null, $start_time, $end_time, null, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }
}
